<script setup lang='ts'>
import { NButton, NSpace, NCard, NDrawer, NDrawerContent, NGrid, NGridItem, NTabs, NTabPane, NInput } from 'naive-ui/es/components'
import { storeToRefs } from 'pinia'
import DetectionService from '~/services/detection.service'
import DefectIdentificationService from '~/services/defect-identification.service'
import { useMessage } from 'naive-ui'
// 引入 Markdown 渲染组件
import { marked } from 'marked'
import { computed } from 'vue'
import config from '~/config'


const layout = useLayoutStore()
const { dialogPlacement } = storeToRefs(layout)
const { t } = useI18n()
const message = useMessage()

// 创建检测服务实例
const detectionService = new DetectionService()
const defectIdentificationService = new DefectIdentificationService()

// 文件列表数据
const mysqlFilesRaw = ref<string[]>([])
const webFilesRaw = ref<string[]>([])

// 搜索关键词
const mysqlSearchKeyword = ref('')
const webSearchKeyword = ref('')

// 逆序排列的文件列表（最新的在前面）
const mysqlFiles = computed(() => {
  const files = [...mysqlFilesRaw.value].reverse()
  if (!mysqlSearchKeyword.value) return files
  return files.filter(file => file.toLowerCase().includes(mysqlSearchKeyword.value.toLowerCase()))
})
const webFiles = computed(() => {
  const files = [...webFilesRaw.value].reverse()
  if (!webSearchKeyword.value) return files
  return files.filter(file => file.toLowerCase().includes(webSearchKeyword.value.toLowerCase()))
})

// 控制drawer显示的变量
const showDetailDrawer = ref(false)

// 当前选中的文件内容
const selectedFileContent = ref('')
const selectedFileName = ref('')

// 添加文件信息对象
const selectedFileInfo = ref({
  name: '',
  content: '',
  type: ''
})

// 检测文件类型
const getFileExtension = (filename: string): string => {
  const parts = filename.split('.')
  return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : ''
}

// 判断文件类型
const fileType = computed(() => {
  const ext = getFileExtension(selectedFileInfo.value.name)
  if (ext === 'html' || ext === 'htm') return 'html'
  if (ext === 'json') return 'json'
  return 'markdown'
})

// 将 Markdown 转换为 HTML
const renderedMarkdown = computed(() => {
  if (selectedFileContent.value && fileType.value === 'markdown') {
    return marked(selectedFileContent.value)
  }
  return ''
})

// 获取MySQL文件列表
async function getMysqlFiles() {
  try {
    mysqlFilesRaw.value = await defectIdentificationService.getMysqlReports()
  } catch (error) {
    message.error('获取MySQL文件列表失败: ' + error.message)
  }
}

// 获取Web文件列表
async function getWebFiles() {
  try {
    webFilesRaw.value = await defectIdentificationService.getWebReports()
  } catch (error) {
    message.error('获取Web文件列表失败: ' + error.message)
  }
}

// Web缺陷识别
async function runWebDetection() {
  try {
    const result = await detectionService.runWebDetection()
    message.success('Web缺陷识别已完成')
    // 重新加载文件列表
    await getWebFiles()
  } catch (error) {
    message.error('Web缺陷识别失败: ' + error.message)
  }
}

// MySQL缺陷识别
async function runMysqlDetection() {
  try {
    const result = await detectionService.runMysqlDetection()
    message.success('MySQL缺陷识别已完成')
    // 重新加载文件列表
    await getMysqlFiles()
  } catch (error) {
    message.error('MySQL缺陷识别失败: ' + error.message)
  }
}

// 处理查看文件内容
async function handleViewFile(fileType: string, filename: string) {
  try {
    selectedFileName.value = filename
    selectedFileContent.value = await defectIdentificationService.getFileContent(fileType, filename)
    // 更新文件信息对象
    selectedFileInfo.value = {
      name: filename,
      content: selectedFileContent.value,
      type: fileType
    }
    showDetailDrawer.value = true
  } catch (error) {
    message.error('获取文件内容失败: ' + error.message)
  }
}

// 刷新MySQL文件列表
async function refreshMysqlFiles() {
  try {
    await getMysqlFiles()
    message.success('MySQL文件列表已刷新')
  } catch (error) {
    message.error('刷新MySQL文件列表失败: ' + error.message)
  }
}

// 刷新Web文件列表
async function refreshWebFiles() {
  try {
    await getWebFiles()
    message.success('Web文件列表已刷新')
  } catch (error) {
    message.error('刷新Web文件列表失败: ' + error.message)
  }
}

// 清空MySQL搜索
function clearMysqlSearch() {
  mysqlSearchKeyword.value = ''
}

// 清空Web搜索
function clearWebSearch() {
  webSearchKeyword.value = ''
}

// JSON格式化函数
function formatJSON(jsonString: string): string {
  try {
    const obj = JSON.parse(jsonString)
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    console.error('JSON解析错误:', e)
    return jsonString
  }
}

// 组件挂载时获取文件列表
onMounted(async () => {
  await getMysqlFiles()
  await getWebFiles()
})
</script>

<template>
  <n-layout class="full-height">
    <n-layout-content class="main-content">
      <n-grid :cols="2" :x-gap="12" :y-gap="12" class="cards-container">
        <!-- MySQL按钮区域 -->
        <n-grid-item>
          <n-space class="button-container" style="justify-content: flex-start;">
            <NButton color="#5CADFF" @click="runMysqlDetection" class="mr-2">
              MySQL缺陷识别
            </NButton>
          </n-space>
        </n-grid-item>
        
        <!-- Web按钮区域 -->
        <n-grid-item>
          <n-space class="button-container" style="justify-content: flex-start;">
            <NButton color="#5CADFF" @click="runWebDetection" class="mr-2">
              Web缺陷识别
            </NButton>
          </n-space>
        </n-grid-item>

        <!-- MySQL文件列表 -->
        <n-grid-item>
          <n-card title="MySQL缺陷识别报告" class="report-card">
            <!-- MySQL搜索和刷新区域 -->
            <div class="search-refresh-container mb-3">
              <n-space align="center">
                <NInput
                  v-model:value="mysqlSearchKeyword"
                  placeholder="搜索MySQL报告文件..."
                  clearable
                  @clear="clearMysqlSearch"
                  style="width: 490px;"
                />
                <NButton color="#5CADFF" size="small" @click="refreshMysqlFiles">
                  刷新
                </NButton>
              </n-space>
            </div>
            
            <div class="card-content">
              <n-scrollbar>
                <n-space vertical>
                  <n-card 
                    v-for="file in mysqlFiles" 
                    :key="file" 
                    class="item-box"
                    hoverable
                  >
                    <div class="flex justify-between items-center">
                      <span>{{ file }}</span>
                      <NButton color="#5CADFF" size="small" @click="handleViewFile('mysql', file)">查看</NButton>
                    </div>
                  </n-card>
                  <div v-if="mysqlFiles.length === 0" class="text-center py-4">
                    {{ mysqlSearchKeyword ? '未找到匹配的MySQL报告' : '暂无MySQL缺陷识别报告' }}
                  </div>
                </n-space>
              </n-scrollbar>
            </div>
          </n-card>
        </n-grid-item>

        <!-- Web文件列表 -->
        <n-grid-item>
          <n-card title="Web缺陷识别报告" class="report-card">
            <!-- Web搜索和刷新区域 -->
            <div class="search-refresh-container mb-3">
              <n-space align="center">
                <NInput
                  v-model:value="webSearchKeyword"
                  placeholder="搜索Web报告文件..."
                  clearable
                  @clear="clearWebSearch"
                  style="width: 490px;"
                />
                <NButton color="#5CADFF" size="small" @click="refreshWebFiles">
                  刷新
                </NButton>
              </n-space>
            </div>
            
            <div class="card-content">
              <n-scrollbar>
                <n-space vertical>
                  <n-card 
                    v-for="file in webFiles" 
                    :key="file" 
                    class="item-box"
                    hoverable
                  >
                    <div class="flex justify-between items-center">
                      <span>{{ file }}</span>
                      <NButton color="#5CADFF" size="small" @click="handleViewFile('web', file)">查看</NButton>
                    </div>
                  </n-card>
                  <div v-if="webFiles.length === 0" class="text-center py-4">
                    {{ webSearchKeyword ? '未找到匹配的Web报告' : '暂无Web缺陷识别报告' }}
                  </div>
                </n-space>
              </n-scrollbar>
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>
    </n-layout-content>

    <!-- 查看文件内容的drawer -->
    <n-drawer v-model:show="showDetailDrawer" :width="'80%'" placement="right">
      <n-drawer-content closable>
        <template #header>
          <h3>{{ selectedFileInfo.name }}</h3>
        </template>
        <n-tabs type="segment">
          <n-tab-pane name="content" tab="内容">
            <!-- Markdown 内容 -->
            <div v-if="fileType === 'markdown'" class="markdown-content">
              <div v-html="renderedMarkdown" style="padding: 10px;"></div>
            </div>
            
            <!-- HTML 内容 -->
            <div v-else-if="fileType === 'html'" class="html-content">
              <div class="html-preview-header">HTML 预览：</div>
              <iframe 
                :srcdoc="selectedFileInfo.content" 
                style="width: 100%; height: 500px; border: 1px solid #ddd; border-radius: 4px;"
                sandbox="allow-same-origin"
              ></iframe>
            </div>
            
            <!-- JSON 内容 -->
            <div v-else-if="fileType === 'json'" class="json-content">
              <div class="json-preview-header">JSON 格式化预览：</div>
              <pre class="json-preview">{{ formatJSON(selectedFileInfo.content) }}</pre>
            </div>
            
            <!-- 其他类型内容 -->
            <div v-else class="markdown-content">
              <div v-html="renderedMarkdown" style="padding: 10px;"></div>
            </div>
          </n-tab-pane>
          <n-tab-pane name="raw" tab="原始内容">
            <p>原始文件内容：</p>
            <pre style="white-space: pre-wrap; word-wrap: break-word; background-color: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 600px; overflow-y: auto;">{{ selectedFileInfo.content }}</pre>
          </n-tab-pane>
          <n-tab-pane name="download" tab="下载">
            <n-button type="primary" tag="a" :href="`${config.defect_identification.base_url}/${selectedFileInfo.type}/reports/${selectedFileInfo.name}`" target="_blank" download>
              下载文件
            </n-button>
            <p style="margin-top: 10px;">点击按钮下载原始文件以保留完整格式</p>
          </n-tab-pane>
        </n-tabs>
      </n-drawer-content>
    </n-drawer>
  </n-layout>
</template>

<style scoped lang='scss'>
.full-height {
  height: 100vh;
}

.main-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.cards-container {
  flex: 1;
  height: 100%;
  min-height: 0;
}

.report-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.card-content {
  flex: 1;
  height: 100%;
  min-height: 0;
}

// 搜索和刷新容器样式
.search-refresh-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 8px;
}

// 按钮容器样式 - 紧贴框
.button-container {
  margin-bottom: 4px;
}

.container {
  padding: 20px;
}

.main-container {
  min-height: 500px;
}

.item-box {
  margin-bottom: 10px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  max-height: 600px;
  overflow-y: auto;
}

// 滚动条样式优化
.n-scrollbar {
  height: 100%;
  
  :deep(.n-scrollbar-rail) {
    right: 2px;
  }
}

// HTML内容样式
.html-content {
  padding: 10px;
  
  .html-preview-header {
    font-weight: bold;
    margin-bottom: 10px;
  }
}

// JSON内容样式
.json-content {
  padding: 10px;
  
  .json-preview-header {
    font-weight: bold;
    margin-bottom: 10px;
  }
  
  .json-preview {
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    max-height: 600px;
    overflow-y: auto;
    font-family: monospace;
  }
}

// Markdown样式
.markdown-content {
  padding: 10px;
  
  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin: 10px 0;
  }
  
  :deep(p) {
    margin: 10px 0;
  }
  
  :deep(ul), :deep(ol) {
    padding-left: 20px;
  }
  
  :deep(li) {
    margin: 5px 0;
  }
  
  :deep(code) {
    background-color: #f5f5f5;
    padding: 2px 4px;
    border-radius: 3px;
  }
  
  :deep(pre) {
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    overflow-x: auto;
    
    code {
      background-color: transparent;
      padding: 0;
    }
  }
  
  :deep(blockquote) {
    border-left: 4px solid #ddd;
    padding-left: 10px;
    margin: 10px 0;
    color: #666;
  }
  
  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 10px 0;
  }
  
  :deep(th), :deep(td) {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
  }
  
  :deep(th) {
    background-color: #f5f5f5;
  }
  
  :deep(img) {
    max-width: 100%;
    height: auto;
  }
}
</style>